<template>
  <div>
    <el-dialog title="编辑" :close-on-click-modal="false" :visible.sync="visible">
      <el-form :model="dataForm" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input readonly v-model="dataForm.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input readonly v-model="dataForm.age" placeholder="年龄"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="identityId">
          <el-input readonly v-model="dataForm.identityId" placeholder="身份证号"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="categoryName">
          <el-input readonly v-model="dataForm.categoryName" placeholder="类别"></el-input>
        </el-form-item>
        <el-form-item label="居住地址" prop="address">
          <el-input readonly v-model="dataForm.address" placeholder="居住地址"></el-input>
        </el-form-item>
        <el-form-item label="对接人" prop="fellowName">
          <el-input readonly v-model="dataForm.fellowName" placeholder="对接人"></el-input>
        </el-form-item>
        <el-form-item label="对接人电话" prop="fellowTel">
          <el-input readonly v-model="dataForm.fellowTel" placeholder="对接人电话"></el-input>
        </el-form-item>
        <el-form-item label="物资及帮助描述" prop="detail">
          <el-input v-model="dataForm.detail" placeholder="物资及帮助描述"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="detailPic" v-model="dataForm.detailPic">
          <el-upload 
            ref="upload" 
            :before-upload="progressA" 
            action="http://localhost:8080/images/upload"
            :http-request="customUpload" 
            :headers="headers" list-type="picture-card" :limit="3" 
            :on-progress="progressA"
            :on-success="handleAvatarSuccess" 
            :on-exceed="handleExceed" 
            :on-preview="handlePictureCardPreview"
            :on-remove="removeImg"
            :file-list="uploadFileList">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">限制上传3张, 只能上传图片，且不超过4M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" title="图片预览">
      <template #content>
        <img :src="dialogImageUrl" style="width: 100%; height: 1300px" alt="预览图片"  @error="handleImageError">
      </template>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 预览大图 -->
    <el-image-viewer 
            v-if="Previewshow" 
            :url-list=preVeiwUrlList 
            :initial-index="initialIndex"
            :on-close="closeImageViewer" 
            :z-index="3000"
            :hide-on-click-modal="true" />
  </div>
</template>

<script>
import service from "@/utils/httpRequest";
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  components: { ElImageViewer },
  data() {
    return {
      visible: false,
      Previewshow: false,
      initialIndex: 0,
      dataForm: {
        id: 0,
        name: "",
        age: 0,
        identityId: "",
        categoryName: "",
        address: "",
        fellowName: "",
        fellowTel: "",
        detail: "",
        detailPic: [],
        activityRecordId: 0
      },
      headers: {},
      uploadFileList: [],
      dialogVisible: false,
      preVeiwUrlList: [],
    };
  },
  computed: {
    // 计算属性
  },
  created() {
    // 创建钩子
  },
  methods: {
    /**     文件正在上传时的钩子    **/
    progressA(event, file) { },
    init(id) {
      this.dataForm.activityRecordId = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields();
        if (this.dataForm.activityRecordId) {
          service({
            method: 'GET',
            url: `/lovehelp/activityrecord/info/${this.dataForm.activityRecordId}`
          }).then(res => {
            if (res.code === 200) {
              this.dataForm = res.activityRecord;
              this.dataForm.detailPic = this.dataForm.detailPic === "" ? [] : this.dataForm.detailPic.split(',');
              this.uploadFileList = this.dataForm.detailPic.map((url, index) => ({
                uid: -index,
                url: url,
                name: url.split('/').pop()
              }));
            }
          });
        }
      });
    },
    dataFormSubmit() {
      service({
        method: 'POST',
        url: '/lovehelp/activityrecord/update',
        data: {
          id: this.dataForm.activityRecordId,
          detail: this.dataForm.detail,
          detailPic: this.dataForm.detailPic.length === 0 ? null : this.dataForm.detailPic.join(',')
        }
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false;
              this.$emit('refreshDataList');
            }
          });
        } else {
          this.$message.error(res.msg);
        }
      }).catch(error => {
        console.error('提交表单出错:', error);
        this.$message.error('提交表单出错，请稍后重试');
      });
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt4M = file.size / 1024 / 1024 < 4;
      if (!isImage) {
        this.$message.error('仅支持上传图片文件（JPG、PNG等）');
        return false;
      }
      if (!isLt4M) {
        this.$message.error('图片大小不能超过4MB');
      }
      return isImage && isLt4M;
    },
    handleAvatarSuccess(res, file) {
      //检查是否超过4M
     if(this.beforeUpload(file)===false){
      //清楚临时文件
      const tempIndex = this.uploadFileList.findIndex(item => item.uid === file.uid);
      if (tempIndex !== -1) {
        this.uploadFileList.splice(tempIndex, 1); // 移除临时文件
      }
      // this.$message.error('图片大小不能超过4MB');
      return
     }
      if (res.code === 200) {
        // 上传成功时，移除临时文件并添加正式文件
        const tempIndex = this.uploadFileList.findIndex(item => item.uid === file.uid);
        if (tempIndex !== -1) {
          this.uploadFileList.splice(tempIndex, 1); // 移除临时文件
        }
        this.dataForm.detailPic.push(res.data.imgurl);
        this.uploadFileList.push({
          uid: file.uid,
          url: res.data.imgurl,
          name: res.data.imgurl.split('/').pop()
        });
        this.$message.success('图片上传成功');
      }
    },
    handleExceed() {
      this.$message.warning('图片仅可上传3张');
    },
    handlePictureCardPreview(file) {
      this.preVeiwUrlList = this.uploadFileList.map(item => item.url);
      console.log(file);
      this.Previewshow = true;
      this.initialIndex = this.uploadFileList.findIndex(item => item.uid === file.uid);     
    },
    closeImageViewer() {
      this.Previewshow = false;
    },
    
    customUpload({ file }) {
      const formData = new FormData();
      formData.append('file', file);
      const tempFile = { uid: file.uid, status: 'uploading', percentage: 0 };
      this.uploadFileList.push(tempFile);
      service.post('/images/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        //上传进度,每300毫秒触发
        onUploadProgress: (progressEvent) => {

          let num = progressEvent.loaded / progressEvent.total * 100 | 0;  //百分比
          const index = this.uploadFileList.findIndex(item => item.uid === file.uid);
          console.log('上传进度:', num);
          if (index !== -1) {
            this.uploadFileList[index].percentage = num;
          }
        }
      }).then(res => {
        if (res.code === 200) {
          this.handleAvatarSuccess(res, file);
        } else {
          this.removeTempFile(file.uid);
          this.$message.error(res.msg || '图片上传失败');
        }
      }).catch(error => {
        this.removeTempFile(file.uid);
        this.$message.error('图片上传失败，请稍后重试');
        console.error('上传错误:', error);
      });
    },
    removeTempFile(uid) {
      const index = this.uploadFileList.findIndex(item => item.uid === uid);
      if (index !== -1) {
        this.uploadFileList.splice(index, 1);
      }
    },
    removeImg(file) {
      const picIndex = this.dataForm.detailPic.findIndex(url => url === file.url);
      const listIndex = this.uploadFileList.findIndex(item => item.uid === file.uid);
      if (picIndex > -1) {
        this.dataForm.detailPic.splice(picIndex, 1);
      }
      if (listIndex > -1) {
        this.uploadFileList.splice(listIndex, 1);
      }
      this.$message.success('图片删除成功');
    },
    handleImageError() {
      this.$message.error('图片加载失败，请检查图片 URL 是否有效。');
    }
  }
};
</script>    